// pages/cards/cards.js
const util = require('../../utils/util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  /*  */
  data: {
    /*  */
    showNoDataIcon:false,
    userInfo_sj: {},
    /*  */
    tabData: [
      {
        tabName: '未使用'
      },
      {
        tabName: '已使用'
      }
    ],
    activeIndex: '0',
    /*  */
    cardListArgs: {
      page: 1,
      pageSize: 5,
      status: '0' //卡片状态:0、未使用，1、已使用
    },
    /* 页码 */
    cardPage: {
      '0': 1,
      '1': 1
    },
    /* 卡片列表数据 */
    cardData: {
      '0': [],
      '1': []
    },
    /*  */
    scanCodeBtn:[
      {
        name:'扫码核销'
      }
    ]
  },
  /* tab切换 */
  menuTabChange: function (e) {
    //console.log(e)
    if (this.data.cardListArgs.type === e.detail.activeIndex) return
    //
    if(!this.data.userInfo_sj.mobile){
      wx.switchTab({
        url: '/pages/personal/personal',
      })
      return
    }
    this.setData({
      'activeIndex': e.detail.activeIndex,
      'cardListArgs.status': e.detail.activeIndex
    })
    if (this.data.cardPage[e.detail.activeIndex + ''] === 1 && !this.data.cardData[e.detail.activeIndex + ''].length) {
      this.getCardForStore()
    }
  },
  /* 获取卡片列表数据 */
  getCardForStore: function (isRefresh) {
    this.setData({
      showNoDataIcon: false
    })
    /* 下拉刷新 */
    if(isRefresh){
      let pageNum = this.data.cardPage[this.data.activeIndex+'']
      let existData = this.data.cardData[this.data.activeIndex+'']
      pageNum = 1
      existData.splice(0,existData.length)
      this.setData({
        [`cardPage.${this.data.activeIndex}`]:pageNum,
        [`cardData.${this.data.activeIndex}`]:existData
      })
    }
    wx.showLoading({
      title: '获取卡片',
      mask: true
    })
    return new Promise((resolve, reject) => {
      this.setData({
        'cardListArgs.status': this.data.activeIndex + '',
        'cardListArgs.page': this.data.cardPage[this.data.activeIndex]
      })
      wx.request({
        url: app.globalData.Url + '/wx/getCardForStore',
        method: 'POST',
        header: this.data.userInfo_sj.header,
        data: util.json2Form(this.data.cardListArgs),   //
        success: res => {
          console.log(res)
          //token失效
          if(app.globalData.check_token(res.data.code))return new Promise((resolve,reject)=>{})
          if (res.data.code == '1') {
            /* 无数据 */
            if (!res.data.body.data.length) {
              if(!this.data.cardData[this.data.activeIndex+''].length){
                this.setData({
                  showNoDataIcon: true
                })
              }
              return resolve()
            }
            /*  */
            let existData = this.data.cardData[this.data.activeIndex + '']
            res.data.body.data.forEach(item => {
              //item.useTimeLong = app.globalData.dateFormat1(item.useEndTime)
              //
              item.timeLong = app.globalData.dateFormat3(item.useStartTime)+'-'+app.globalData.dateFormat3(item.useEndTime)
              item.useTime = app.globalData.dateFormatYMDHM(item.useTime)
              existData.push(item)
            })
            /*  */
            let pageNum = this.data.cardPage[this.data.activeIndex+'']*1
            pageNum+=1
            /*  */
            this.setData({
              [`cardPage.${this.data.activeIndex}`]: pageNum,
              [`cardData.${this.data.activeIndex}`]: existData
            })
            resolve()
          } else {
            wx.showToast({
              icon: 'none',
              title: '' + res.data.msg
            })
            if(!this.data.cardData[this.data.activeIndex+''].length){
              this.setData({
                showNoDataIcon: true
              })
            }
            reject()
          }
        },
        fail: err => {
          console.log(err)
          wx.showToast({
            icon: 'none',
            title: '获取数据失败'
          })
          if(!this.data.cardData[this.data.activeIndex+''].length){
            this.setData({
              showNoDataIcon: true
            })
          }
          reject()
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
  },
  /*  */
  showPrice: function(e){
    let { price } = e.currentTarget.dataset
    wx.showToast({
      icon:'none',
      title:'￥'+price
    })
  },
  /*  */
  showCardDetail: function(e){
    let { info, index } = e.currentTarget.dataset
    app.globalData.setNeedAnimation.call(this, `cardData.${this.data.activeIndex}`,this.data.cardData[this.data.activeIndex+''],index).then(()=>{
      //console.log(info)
      wx.navigateTo({
        url:'/pages/card-detail/card-detail',
        success: res=>{
          res.eventChannel.emit('open-card-detail',{
            info:info,
            activeIndex:this.data.activeIndex
          })
        }
      })
    })
  },
  /* scanCode */
  openScanCode: function(e){
    let { index } = e.currentTarget.dataset
    app.globalData.setNeedAnimation.call(this, 'scanCodeBtn', this.data.scanCodeBtn,index).then(()=>{
      wx.showLoading({
        title: '扫描卡券',
        mask:true
      })
      return new Promise((resolve, reject)=>{
        wx.scanCode({
          success: res=>{
            resolve(res)
          },
          fail: err => {
            reject()
          }
        })
      })
    }).then(data=>{
      console.log(data)
      return new Promise((resolve, reject)=>{
        wx.request({
          url: app.globalData.Url + '/wx/getCardInfoForCode',
          method: 'POST',
          header: this.data.userInfo_sj.header,
          data: util.json2Form({
            code: data.result
          }),   //
          success: res => {
            console.log(res)
            //token失效
            if(app.globalData.check_token(res.data.code))return new Promise((resolve,reject)=>{})
            if (res.data.code == '1') {
              //清空列表数据
              this.setData({
                'cardPage.0':1,
                'cardData.0':[],
                'cardPage.1':1,
                'cardData.1':[]
              })
              //刷新列表
              this.getCardForStore(true).then(()=>{
                wx.showToast({
                  title:'核销成功'
                })
              })
              resolve()
            } else {
              reject(res.data.msg)
            }
          },
          fail: err => {
            console.log(err)
            wx.showToast({
              icon: 'none',
              title: '获取数据失败'
            })
            reject()
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      })
    }).then(()=>{
      wx.hideLoading()
    }).catch(err=>{
      wx.hideLoading()
      if(err){
        wx.showModal({
          title:'提示',
          content:''+err,
          showCancel: false
        })
      }else{
        wx.showModal({
          title:'提示',
          content:'扫码核销卡券失败',
          showCancel: false
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取用户信息
    this.setData({
      userInfo_sj: app.globalData.get_userInfo()
    })
    console.log(this.data.userInfo_sj)
    //
    // this.setData({
    //   'cardListArgs.storeid': this.data.userInfo_sj.storeId
    // })
    //
    if(this.data.userInfo_sj.mobile&&!this.data.cardData[this.data.activeIndex+''].length){
      this.getCardForStore()
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getCardForStore(true).then(()=>{
      wx.stopPullDownRefresh({
        complete: (res) => {},
      })
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getCardForStore()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})